package me.pplay.playtalk.database;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;


public class DbHelper extends SQLiteOpenHelper {

	private final static String dbName 		= "palytalk";
	private final String USERINFO_TBNAME 	= "userinfo";
	private final String CHATLIST_TBNAME	= "chatlist";
	private final String FRIEND_TBNAME		= "friend";
	private final String NOTIFICATION_TABLE	= "notification";
	private final static int VERSION		= 1;
	public SQLiteDatabase db = null;

	public DbHelper(Context context) {
		super(context, dbName, null, VERSION);
	}

	public DbHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);

	}

	/**
	 * 打开数据库
	 */
	public void openDatabase() {
		db = this.getWritableDatabase();
	}

	/**
	 * 关闭数据库
	 */
	public void closeDatabase() {
		if (db != null) {
			db.close();
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		createUserinfoTable(db);
		createChatListTable(db);
		createFriendTable(db);
		createNitification(db);
		closeDatabase();
	}

	private void createUserinfoTable(SQLiteDatabase db) {
		
		String sql = "create table " + USERINFO_TBNAME + "("
				+ "skyid integer primary key, name text, alias text, server_alias text, icon text,birthday text,"
				+ "country text,signature text, pnum text, sex integer, age integer, searchvisible integer,"
				+ "status integer, lanstr text, lan text, avatarid text, avatar_sid text, avatar_fpath text)";
		db.execSQL(sql);
	}

	/**
	 * type 1:点对点  
	 * type 2:群会话   
	 * @param db
	 */
	private void createChatListTable(SQLiteDatabase db){
		String sql = "create table " + CHATLIST_TBNAME + "("
				+ "_id integer primary key, myskyid integer, type integer, skyid integer,  name text, time text, count integer)";
		db.execSQL(sql);
	}

	/**
	 * 好友 1:同意 2：拒绝  3 请求加好友  4好友状态（上下线）
	 */
	private void createFriendTable(SQLiteDatabase db){
		String sql = "create table " + FRIEND_TBNAME + "("
				+ "_id integer primary key, myskyid integer,type integer, skyid integer, name text, icon text, message text,time text)";
		db.execSQL(sql);
	}
	
	/**
	 * 通知
	 */
	
	private void createNitification(SQLiteDatabase db){
		String sql = "create table " +NOTIFICATION_TABLE + "("
				+ "_id integer primary key, type integer, content text, time text)";
		db.execSQL(sql);
	}
	
	/**
	 * 更新数据库版本
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("drop table if exists " + USERINFO_TBNAME);
		db.execSQL("drop table if exists " + CHATLIST_TBNAME);
		db.execSQL("drop table if exists " + FRIEND_TBNAME);
		db.execSQL("drop table if exists " + NOTIFICATION_TABLE);
		onCreate(db);
	}

	



}
